package com.xbdun.service.bmp.service.system.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xbdun.common.api.Client;
import com.xbdun.common.enums.UserRolesEnums;
import com.xbdun.common.enums.XbdunPkgEnum;
import com.xbdun.common.exceptions.BizException;
import com.xbdun.common.page.Pager;
import com.xbdun.common.qr.LoginMacResponse;
import com.xbdun.common.util.CommonUtil;
import com.xbdun.common.util.DateUtil;
import com.xbdun.dao.bmp.dto.LoginCanPagesDto;
import com.xbdun.dao.bmp.dto.LoginOrgUserMenuDto;
import com.xbdun.dao.bmp.dto.OrgUserDto;
import com.xbdun.dao.bmp.dto.QueryOrgUsersDto;
import com.xbdun.dao.bmp.dto.open.JoinOrgCodeByCodeDto;
import com.xbdun.dao.bmp.dto.open.OrgUserBkgeDto;
import com.xbdun.dao.bmp.entity.XbdunOrgInviteCodeDo;
import com.xbdun.dao.bmp.entity.XbdunOrgUserDo;
import com.xbdun.dao.bmp.entity.XbdunSysUserDo;
import com.xbdun.dao.bmp.mapper.OrgInviteCodeMapper;
import com.xbdun.dao.bmp.mapper.OrgUserMapper;
import com.xbdun.dao.bmp.mapper.OrleDepartMapper;
import com.xbdun.dao.bmp.mapper.PowerUserMenuMapper;
import com.xbdun.dao.bmp.mapper.SysUserMapper;
import com.xbdun.facade.bmp.constant.CommonConst;
import com.xbdun.facade.bmp.enumx.PlatTypeEnum;
import com.xbdun.facade.bmp.enumx.SysOrgEnum.SpecilRoleEnum;
import com.xbdun.facade.bmp.enumx.SysOrgEnum.SysOrgEnableEnum;
import com.xbdun.facade.bmp.enumx.SysOrgEnum.SysOrgInvitTypeEnum;
import com.xbdun.facade.bmp.enumx.UserEnum.UserEffectEnum;
import com.xbdun.facade.bmp.enumx.UserEnum.UserInauTypeEnum;
import com.xbdun.facade.bmp.exceptions.BmpBizException;
import com.xbdun.facade.bmp.request.open.CreateUserByInviteCodeRequest;
import com.xbdun.facade.bmp.request.system.LoginCanPagesRequest;
import com.xbdun.facade.bmp.request.system.ModifyOrgUserRequest;
//192.168.0.11:8088/gitbucket/git/bmp/xbdun-service-bmp.git
import com.xbdun.facade.bmp.request.system.ModifyUserPowerRequest;
import com.xbdun.facade.bmp.request.system.OrgUserPagerRequest;
import com.xbdun.facade.bmp.request.system.OrgUserPowerMenuRequest;
import com.xbdun.facade.bmp.request.system.OrgUserRequest;
import com.xbdun.facade.bmp.request.system.QueryOrgUsersRequest;
import com.xbdun.facade.bmp.request.system.UserSpecialPowerRequest;
import com.xbdun.facade.bmp.response.open.CreateUserByInviteCodeResponse;
import com.xbdun.facade.bmp.response.open.OrgUserBkgeResponse;
import com.xbdun.facade.bmp.response.system.LoginOrgUserMenuResponse;
import com.xbdun.facade.bmp.response.system.OrgUserPagerResponse;
import com.xbdun.facade.bmp.response.system.OrgUserResponse;
import com.xbdun.facade.bmp.response.system.QueryOrgUsersResponse;
import com.xbdun.facade.bmp.result.user.CreateUserByInviteCodeResult;
import com.xbdun.service.bmp.biz.SysUserBiz;
import com.xbdun.service.bmp.service.system.OrgUserService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class OrgUserServiceImpl implements OrgUserService {

	@Autowired
	OrgUserMapper orgUserMapper;
	@Autowired
	SysUserBiz sysUserBiz;
	@Autowired
	SysUserMapper sysUserMapper;
	@Autowired
	OrgInviteCodeMapper orgInviteCodeMapper;
	@Autowired
	PowerUserMenuMapper powerUserMenuMapper;
	@Autowired
	OrleDepartMapper orleDepartMapper;
	
	@Transactional
	public void addOrgUser(OrgUserRequest request, Client client) throws Exception{
		XbdunSysUserDo xbdunSysUserDo = null;
		XbdunOrgUserDo xbdunOrgUserDo = null;
		//判断员工的员工号或者邮件
		if(0!=orgUserMapper.existJobNum(request.getJonNum(),request.getOrgEmail(),client.getOrgCode())){
			throw BmpBizException.DATA_EXIST.newInstance("员工号或者邮件已经在本机构下存在了");
		}
		//根据用户身份证判断用户是否已经存在
		Long userCode = sysUserBiz.getByIdCard(request.getIdCard());
		//查询平台用户是否已经存在
		if(null==userCode||userCode.longValue()<=0){
			xbdunSysUserDo = new XbdunSysUserDo();
			
			xbdunSysUserDo.setRealName(request.getRealName());
			xbdunSysUserDo.setSex(request.getSex());
			xbdunSysUserDo.setIdCard(request.getIdCard());
			xbdunSysUserDo.setBirthDate(request.getBirthDate());
			xbdunSysUserDo.setUserName(request.getRealName());
			xbdunSysUserDo.setMobile(request.getMobile());//设置手机
			xbdunSysUserDo.setEmail(request.getOrgEmail());//设置邮箱
			xbdunSysUserDo.setEducation(request.getEducation());//设置学历
			xbdunSysUserDo.setIdCard(request.getIdCard());//设置IDCard
			xbdunSysUserDo.setImgUrl(request.getImgUrl());//设置头像
			xbdunSysUserDo.setType(UserRolesEnums.MEMBER.getKey());//默认第一次用户的注册肯定是超级管理员
			xbdunSysUserDo.setCreateTime(new Date());
			//默认密码为身份证后六位
			xbdunSysUserDo.setPwd(CommonUtil.settingPwd(request.getIdCard().substring(request.getIdCard().length()-6,request.getIdCard().length()),DateUtil.formatDate(xbdunSysUserDo.getCreateTime())));
			sysUserBiz.getSysUserOrCreate(xbdunSysUserDo, request.getMobile());
			userCode = xbdunSysUserDo.getUserCode();
		}else{
			//判断当前用户是否已在当前机构下
			if(0!=orgUserMapper.existOrgUser(userCode,client.getOrgCode())){
				throw BizException.DB_INSERT_RESULT_0.newInstance("新增机构用户失败，原因是当前用户已在该机构");
			}
		}
		
		//创建机构用户
		xbdunOrgUserDo = new XbdunOrgUserDo();
		xbdunOrgUserDo.setOrgCode(client.getOrgCode());
		xbdunOrgUserDo.setUserCode(userCode);
		xbdunOrgUserDo.setSpecilRole(request.getSpecilRole());
		xbdunOrgUserDo.setState(request.getState());
		xbdunOrgUserDo.setEnabled(request.getEnabled());
		xbdunOrgUserDo.setMobile(request.getMobile());
		xbdunOrgUserDo.setOrgEmail(request.getOrgEmail());
		xbdunOrgUserDo.setInauType(request.getInauType());
		xbdunOrgUserDo.setInvitType(request.getInvitType());
		xbdunOrgUserDo.setJonNum(request.getJonNum());
		xbdunOrgUserDo.setRealName(request.getRealName());
		xbdunOrgUserDo.setUserId(CommonUtil.generateOrgUserId(client.getOrgCode(), userCode));
		
		orgUserMapper.addXbdunOrgUser(xbdunOrgUserDo);
		
		//是否发放邀请码
		if(request.getInvitType()>1){
			//创建邀请码
			XbdunOrgInviteCodeDo xbdunOrgInviteCodeDo = new XbdunOrgInviteCodeDo();
			
			xbdunOrgInviteCodeDo.setCreateTime(new Date());
			xbdunOrgInviteCodeDo.setIdCard(request.getIdCard());
			xbdunOrgInviteCodeDo.setInviteCode(RandomStringUtils.randomNumeric(6));
			xbdunOrgInviteCodeDo.setOrgCode(client.getOrgCode());
			xbdunOrgInviteCodeDo.setUserCode(userCode);
			xbdunOrgInviteCodeDo.setPlatType((request.getPlatType()<=0?PlatTypeEnum.SALESMAN.getKey():request.getPlatType()));
			//邀请码有效期,过了这个有效期，那么就视为无效,就需要企业在此发放
			xbdunOrgInviteCodeDo.setEndTime(DateUtil.addDay(xbdunOrgInviteCodeDo.getCreateTime(), CommonConst.INVITE_CODE_DAT));
			
			//写入邀请码表信息
			orgInviteCodeMapper.addXbdunOrgInviteCode(xbdunOrgInviteCodeDo);
		}
	}
	
	@Transactional
	public void addUserDptRolePower(ModifyUserPowerRequest request, Client client) throws Exception {
		XbdunOrgUserDo byUserId = orgUserMapper.getByUserId(request.getUserId());
		if(null ==byUserId){
			throw BizException.DB_SELECTONE_IS_NULL.newInstance("操作的用户不存在");
		}
		if(byUserId.getOrgCode()!=client.getOrgCode()){
			throw BizException.POWER_FAIL.newInstance("对不起该用户不属于您机构下，您没有权限操作");
		}
		//一般权限
		if(CollectionUtils.isNotEmpty(request.getRdpIds())){
			int chekRoleDepartOk = orleDepartMapper.chekRoleDepartOk(client.getOrgCode(), request.getDepartCode(), request.getRdpIds());
			if(chekRoleDepartOk!=request.getRdpIds().size()){
				throw BmpBizException.DEF_ERROR.newInstance("设置的角色部分不属于系统关联角色");
			}
			powerUserMenuMapper.addOrgUserMenu(byUserId.getUserCode(), client.getOrgCode(),request.getDepartCode(),request.getRdpIds());
			//获取机构用户可登平台
			String plats = powerUserMenuMapper.getHasPlats(byUserId.getUserCode(),client.getOrgCode());
			//修改机构用户可登平台
			StringUtils.defaultIfBlank(plats, "");
			orgUserMapper.updateOrgUserHasPlats(byUserId.getUserCode(), client.getOrgCode(),plats);
		}
	}
	
	@Transactional
	public void delUserDptRolePower(ModifyUserPowerRequest request, Client client) throws Exception {
		XbdunOrgUserDo byUserId = orgUserMapper.getByUserId(request.getUserId());
		if(null ==byUserId){
			throw BizException.DB_SELECTONE_IS_NULL.newInstance("操作的用户不存在");
		}
		if(byUserId.getOrgCode()!=client.getOrgCode()){
			throw BizException.POWER_FAIL.newInstance("对不起该用户不属于您机构下，您没有权限操作");
		}
		//一般权限
		if(CollectionUtils.isNotEmpty(request.getRdpIds())){
			powerUserMenuMapper.delOrgUserMenu(byUserId.getUserCode(), client.getOrgCode(), request.getRdpIds());
			//获取机构用户可登平台
			String plats = powerUserMenuMapper.getHasPlats(byUserId.getUserCode(),client.getOrgCode());
			//修改机构用户可登平台
			StringUtils.defaultIfBlank(plats, "");
			orgUserMapper.updateOrgUserHasPlats(byUserId.getUserCode(), client.getOrgCode(),plats);
		}
	}
	
	@Transactional
	public void modifyUserSpecialPower(UserSpecialPowerRequest request, Client client) throws Exception {
		XbdunOrgUserDo byUserId = orgUserMapper.getByUserId(request.getUserId());
		if(null ==byUserId){
			throw BizException.DB_SELECTONE_IS_NULL.newInstance("操作的用户不存在");
		}
		if(byUserId.getOrgCode()!=client.getOrgCode()){
			throw BizException.POWER_FAIL.newInstance("对不起该用户不属于您机构下，您没有权限操作");
		}
		//新增特殊权限
		if(CollectionUtils.isNotEmpty(request.getAddPowers())){
			powerUserMenuMapper.delOrgUserSpecil(byUserId.getUserCode(), client.getOrgCode(),request.getAddPowers());
			powerUserMenuMapper.addOrgUserSpecil(byUserId.getUserCode(), client.getOrgCode(),request.getAddPowers(),1);
		}
		//删除特殊权限
		if(CollectionUtils.isNotEmpty(request.getDelPowers())){
			powerUserMenuMapper.delOrgUserSpecil(byUserId.getUserCode(), client.getOrgCode(),request.getDelPowers());
			powerUserMenuMapper.addOrgUserSpecil(byUserId.getUserCode(), client.getOrgCode(),request.getDelPowers(),2);
		}
		
		//获取机构用户可登平台
		String plats = powerUserMenuMapper.getHasPlats(byUserId.getUserCode(),client.getOrgCode());
		//修改机构用户可登平台
		StringUtils.defaultIfBlank(plats, "");
		orgUserMapper.updateOrgUserHasPlats(byUserId.getUserCode(), client.getOrgCode(),plats);
	}
	
	
	public Pager<OrgUserPagerResponse> queryOrgUserPager(OrgUserPagerRequest request, Client client) throws Exception {
		
		Pager<OrgUserPagerResponse> resultPager = request.newPager(OrgUserPagerResponse.class);
		//查询参数
		Map<String,Object> where  = new HashMap<String,Object>();
		where.put("orgCode", client.getOrgCode());
		
		if (null!=request.getDepartCode()&&request.getDepartCode().longValue()>0) {
			where.put("departCode",request.getDepartCode());										//部门
		}
		if (request.getInauType() != 0) {
			where.put("inauType",request.getInauType());											//用户公司状态;正式【1】，临时【2】，实习【3】;其他【4】默认
		}
		if (request.getState() != 0) {
			where.put("state", request.getState());													// 状态;已生效【1】默认，未生效【2】
		}
		if (request.getSelectKey()>0&&StringUtils.isNotBlank(request.getSelectVal())) {
			where.put("selectKey",request.getSelectKey());
			where.put("selectValue",request.getSelectVal());
		}
		//开始时间
		if(null!=request.getStartTime()){
			where.put("startTime",request.getStartTime());
		}
		//结束时间
		if(null!=request.getEndTime()){
			where.put("endTime",request.getEndTime());
		}
		
		//选项机构下关联的用户
		int resultCnt = orgUserMapper.queryPagerCount(where);
		if(resultCnt==0){
			where.clear();
			resultPager.setTotalCount(0);
			return resultPager;
		}
		//排序
		if(StringUtils.isBlank(request.getOrderBy())){
			request.setOrderBy(" createTime DESC");
		}
		//查询返回机构下的用户
		List<OrgUserDto> list = orgUserMapper.queryPager(where,request.getOrderBy(),(request.getPageIndex()-1)*request.getPageSize(), request.getPageSize());
		if(CollectionUtils.isNotEmpty(list)){
			resultPager.setData(new ArrayList<OrgUserPagerResponse>());
			OrgUserPagerResponse infoRes = null;
			try{
				for(OrgUserDto info : list){
					infoRes = new OrgUserPagerResponse();
					BeanUtils.copyProperties(infoRes, info);
					resultPager.getData().add(infoRes);
				}
			}catch(Exception e){
				log.error("企业信息查询组合list异常",e);
			}finally{
				list.clear();
				where.clear();
			}
		}
		//设置查询条数
		resultPager.setTotalCount(resultCnt);
		resultPager.setPager();
		where.clear();
		return resultPager;
	}
	
	public List<String> queryOrgUserPower(OrgUserPowerMenuRequest request, Client client)throws Exception{
		XbdunOrgUserDo byUserId = orgUserMapper.getByUserId(request.getUserId());
		if(null ==byUserId){
			throw BizException.DB_SELECTONE_IS_NULL.newInstance("操作的用户不存在");
		}
		if(byUserId.getOrgCode()!=client.getOrgCode()){
			throw BizException.POWER_FAIL.newInstance("对不起该用户不属于您机构下，您没有权限操作");
		}
		switch(request.getType()){
			case 0:
				//查询出机构下当前用户的所有权限
				return orgUserMapper.queryOrgUserPower(byUserId.getUserCode(),client.getOrgCode());
			case 1:
				//机构下员工的部门角色权限
				return powerUserMenuMapper.queryOrgUserPower(byUserId.getUserCode(),client.getOrgCode());
			default:
				throw BmpBizException.PARAM_CHKE_FAIL.newInstance("查询用户的权限类型系统未定义%s", request.getType());
		}
	}
	
	public List<LoginOrgUserMenuResponse> loginOrgUserMenu(Client client) {
		List<LoginOrgUserMenuResponse> result= null;
		List<LoginOrgUserMenuDto> list = null;
		//获取到当前用户的角色是平台管理员
		if(UserRolesEnums.isXbdAdmin(client.getRoleId())){
			//如果为基础数据平台,获取的是默认菜单
			if(client.getPlatCode()==100){
				list = orgUserMapper.loginXbdunDefMenu();
			}else{
				//获取平台所有的菜单
				list = orgUserMapper.loginXbdunPlatCodeMenu(client.getPlatCode());
			}
		}else if(UserRolesEnums.isSupperAdmin(client.getRoleId())||UserRolesEnums.isAdmins(client.getRoleId())){
			list = orgUserMapper.loginOrgSupAdMenu(client.getPlatCode(),client.getOrgCode());
		}else{
			list = orgUserMapper.loginOrgUserMenu(client.getPlatCode(),Long.valueOf(client.getUserCode()),client.getOrgCode());
		}
		if(CollectionUtils.isNotEmpty(list)){
			result = new ArrayList<LoginOrgUserMenuResponse>();
			LoginOrgUserMenuResponse infoRes = null;
			try{
				for(LoginOrgUserMenuDto info : list){
					infoRes = new LoginOrgUserMenuResponse();
					BeanUtils.copyProperties(infoRes, info);
					result.add(infoRes);
				}
			}catch(Exception e){
				log.error("用户登录获取个人菜单转换异常,入参={},异常={}",client,e);
			}finally{
				list.clear();
				list = null;
			}
		}
		
		return result;
	}

	public OrgUserResponse getOrgUserInfo(String userId,Client client) {
		XbdunOrgUserDo byUserId = orgUserMapper.getByUserId(userId);
		if(null ==byUserId){
			throw BizException.DB_SELECTONE_IS_NULL.newInstance("操作的用户不存在");
		}
		if(byUserId.getOrgCode()!=client.getOrgCode()){
			throw BizException.POWER_FAIL.newInstance("对不起该用户不属于您机构下，您没有权限操作");
		}
		
		XbdunSysUserDo xbdunSysUserDo = sysUserBiz.getByUserCode(byUserId.getUserCode());
		
		OrgUserResponse orgUserInfo = new OrgUserResponse();
		orgUserInfo.setRealName(byUserId.getRealName());
		orgUserInfo.setInauType(byUserId.getInauType());
		orgUserInfo.setState(byUserId.getState());
		orgUserInfo.setInvitType(byUserId.getInvitType());
		orgUserInfo.setJonNum(byUserId.getJonNum());
		orgUserInfo.setOrgEmail(byUserId.getOrgEmail());
		orgUserInfo.setMobile(byUserId.getMobile());
		orgUserInfo.setEnabled(byUserId.getEnabled());
		orgUserInfo.setSpecilRole(byUserId.getSpecilRole());
		
		orgUserInfo.setSex(xbdunSysUserDo.getSex());
		orgUserInfo.setQq(xbdunSysUserDo.getQq());
		orgUserInfo.setImgUrl(xbdunSysUserDo.getImgUrl());
		orgUserInfo.setEducation(xbdunSysUserDo.getEducation());
		orgUserInfo.setIdCard(xbdunSysUserDo.getIdCard());
		orgUserInfo.setBirthDate(xbdunSysUserDo.getBirthDate());
		
		// 设置部门角色
		List<String> list = orgUserMapper.getOrgUserDepartRole(byUserId.getUserCode(),byUserId.getOrgCode());
		if (list != null) {
			StringBuilder sb = new StringBuilder();
			boolean bl = false;
			for (String str : list) {
				if(bl)sb.append(",");
				sb.append(str);
				if(!bl)bl = true;
			}
			orgUserInfo.setDepartRole(sb.toString());
		}
		
		return orgUserInfo;
	}

	public void modifyOrgUserById(ModifyOrgUserRequest request, Client client)throws Exception {
		XbdunOrgUserDo byUserId = orgUserMapper.getByUserId(request.getUserId());
		if(null ==byUserId){
			throw BizException.DB_SELECTONE_IS_NULL.newInstance("操作的用户不存在");
		}
		if(byUserId.getOrgCode()!=client.getOrgCode()){
			throw BizException.POWER_FAIL.newInstance("对不起该用户不属于您机构下，您没有权限操作");
		}
		
		//客户端为管理员,修改用户角色不小于管理员
		if(UserRolesEnums.isAdmin(client.getRoleId())&&byUserId.getSpecilRole()!=0){
			throw BizException.POWER_FAIL.newInstance("修改失败,权限不足");
		}
		
		XbdunOrgUserDo busiPer = orgUserMapper.getOrgBusiPerson(client.getOrgCode());
		if(busiPer!=null){
		}else{
			throw BizException.DB_SELECTONE_IS_NULL.newInstance("系统繁忙,未找到当前企业的企业法人");
		}
		
		if(busiPer.getUserId().equals(byUserId.getUserId())&&!busiPer.getUserId().equals(client.getUserId())){
			throw BizException.DB_UPDATE_RESULT_0.newInstance("修改失败,原因是企业法人不能禁用");
		}
		
		Map<String,Object> param = new HashMap<String,Object>();
		if(StringUtils.isNotBlank(request.getRealName())){
			param.put("realName", request.getRealName());
		}
		if(StringUtils.isNotBlank(request.getMobile())){
			param.put("mobile", request.getMobile());
		}
		if(StringUtils.isNotBlank(request.getJonNum())){
			param.put("jonNum", request.getJonNum());
		}
		if(StringUtils.isNotBlank(request.getOrgEmail())){
			param.put("orgEmail", request.getOrgEmail());
		}
		if (null != SysOrgEnableEnum.getEnum(request.getEnabled())) {
			if(busiPer.getUserId().equals(byUserId.getUserId())&&SysOrgEnableEnum.OFF.getKey()==request.getEnabled()){
				throw BizException.DB_UPDATE_RESULT_0.newInstance("修改失败,原因是企业法人不能停用");
			}
			param.put("enabled", request.getEnabled());
		}
		if (null != SpecilRoleEnum.getEnum(request.getSpecilRole())) {
			param.put("specilRole", request.getSpecilRole());
		}
		if (null != UserInauTypeEnum.getEnum(request.getInauType())) {
			param.put("inauType", request.getInauType());
		}
		if (null != SysOrgInvitTypeEnum.getEnum(request.getInvitType())) {
			param.put("invitType", request.getInvitType());
		}
		if (null != UserEffectEnum.getEnum(request.getState())) {
			if(busiPer.getUserId().equals(byUserId.getUserId())){
				throw BizException.DB_UPDATE_RESULT_0.newInstance("修改失败,原因是当前用户为企业法人");
			}
			param.put("state", request.getState());
		}
		
		Map<String, Object> where = new HashMap<String, Object>();
		where.put("userId", byUserId.getUserId());
		where.put("version", byUserId.getVersion());
		
		if (orgUserMapper.modifyOrgUserById(param, where)==0) {
			where.clear();
			param.clear();
			where = null;
			param = null;
			throw BizException.DB_UPDATE_RESULT_0.newInstance("修改当前用户失败");
		}
		
		where.clear();
		param.clear();
		if(StringUtils.isNotBlank(request.getImgUrl())){
			param.put("imgUrl", request.getImgUrl());
		}
		if(null!=request.getBirthDate()){
			param.put("birthDate", request.getBirthDate());
		}
		if(request.getSex()!=0){
			param.put("sex", request.getSex());
		}
		if(request.getEducation()!=0){
			param.put("education", request.getEducation());
		}
		
		if(MapUtils.isNotEmpty(param)){
			XbdunSysUserDo currentUser = sysUserMapper.getByUserCode(byUserId.getUserCode());
			if(currentUser==null){
				throw BizException.DB_SELECTONE_IS_NULL.newInstance("当前机构用户不存在平台用户");
			}
			where.put("userCode", currentUser.getUserCode());
			where.put("version", currentUser.getVersion());
			//修改机构用户
			sysUserMapper.updateUserInfo(param,where);
		}
		where.clear();
		param.clear();
		where = null;
		param = null;
	}

	public void deleteOrgUser(String userId, Client client) {
		XbdunOrgUserDo byUserId = orgUserMapper.getByUserId(userId);
		if(null ==byUserId){
			throw BizException.DB_SELECTONE_IS_NULL.newInstance("操作的用户不存在");
		}
		if(byUserId.getOrgCode()!=client.getOrgCode()){
			throw BizException.POWER_FAIL.newInstance("对不起该用户不属于您机构下，您没有权限操作");
		}
		//判断删除的员工是否可以删除(supperAdmin+admins和企业法人不可删除)
		if(UserRolesEnums.isSupperAdmin(byUserId.getSpecilRole())||UserRolesEnums.isAdmins(byUserId.getSpecilRole())){
			throw BizException.DB_UPDATE_RESULT_0.newInstance("删除失败,原因是当前员工为"+UserRolesEnums.getEnum(byUserId.getSpecilRole()));
		}
		
		XbdunOrgUserDo busiPer = orgUserMapper.getOrgBusiPerson(client.getOrgCode());
		if(busiPer!=null){
			if(busiPer.getUserId().equals(byUserId.getUserId())){
				throw BizException.DB_UPDATE_RESULT_0.newInstance("删除失败,原因是当前员工为企业法人");
			}
		}else{
			throw BizException.DB_SELECTONE_IS_NULL.newInstance("系统繁忙,未找到当前企业的企业法人");
		}
		
		if (orgUserMapper.deleteOrgUser(userId,byUserId.getVersion())==0){
			throw BmpBizException.DB_UPDATE_RESULT_0.newInstance("删除当前用户失败!");
		}
	}
	public Pager<QueryOrgUsersResponse> queryOrgUsersPager(QueryOrgUsersRequest request) {
		Pager<QueryOrgUsersResponse> resultPager = request.newPager(QueryOrgUsersResponse.class);
		//选项机构下关联的用户
		int resultCnt = orgUserMapper.queryOrgUsersPagerCnt(request.getUserCode());
		if(resultCnt==0){
			resultPager.setTotalCount(0);
			return resultPager;
		}
		//查询返回机构下的用户
		List<QueryOrgUsersDto> list = orgUserMapper.queryOrgUsersPager(request.getUserCode(),(request.getPageIndex()-1)*request.getPageSize(), request.getPageSize());
		if(CollectionUtils.isNotEmpty(list)){
			resultPager.setData(new ArrayList<QueryOrgUsersResponse>());
			QueryOrgUsersResponse infoRes = null;
			try{
				for(QueryOrgUsersDto info : list){
					infoRes = new QueryOrgUsersResponse();
					BeanUtils.copyProperties(infoRes, info);
					infoRes.setRoleId(info.getSpecilRole());
					resultPager.getData().add(infoRes);
				}
			}catch(Exception e){
				log.error("企业信息查询组合list异常",e);
			}finally{
				list.clear();
			}
		}
		//设置查询条数
		resultPager.setTotalCount(resultCnt);
		resultPager.setPager();
		return resultPager;
	}

	public List<LoginMacResponse> loginCanPages(LoginCanPagesRequest request)throws Exception {
		List<LoginCanPagesDto> loginCanPages = null;
		List<LoginMacResponse> result = null;
		//判断登录用户是否为平台管理用户
		Integer roleId = orgUserMapper.getOrgUserRoleId(request.getOrgCode(),request.getUserCode());
		if(null ==  roleId ||roleId.intValue()<=0){
			throw BizException.DB_SELECTONE_IS_NULL.newInstance("当前用户所属机构角色未系统未定义");
		}
		//如果机构相同，并且有时平台管理员，那么就需要直接返回所有的有效登录平台列表
		if(UserRolesEnums.isXbdAdmin(roleId.intValue())){
			loginCanPages = orgUserMapper.xbdunCanPages();
		}else{
			//根据当前用户登录的角色判断当前用户应该出现什么样的菜单
			if (UserRolesEnums.isSupperAdmin(roleId.intValue())||UserRolesEnums.isAdmins(roleId.intValue())) {
				//如果是超级管理员
				loginCanPages = orgUserMapper.supperCanPages(request.getOrgCode());
			}else{
				//普通管理员以及员工
				loginCanPages = orgUserMapper.loginCanPages(request.getOrgCode(),request.getUserCode());
			}
		}
		if(CollectionUtils.isNotEmpty(loginCanPages)){
			LoginMacResponse info = null;
			result = new ArrayList<LoginMacResponse>();
			for(LoginCanPagesDto dto:loginCanPages){
				info = new LoginMacResponse();
				BeanUtils.copyProperties(info, dto);
				//设置密钥KEY
				info.setSecretKey(String.valueOf(dto.getSecretKey()));
				info.setDataMac(dto.getSecretVal());//平台密钥
				result.add(info);
			}
		}
		return result;
	}
	
	public QueryOrgUsersResponse getUserByOrgUserCode(Long orgCode, Long userCode)throws Exception{
		QueryOrgUsersResponse resp = null;
		QueryOrgUsersDto result = orgUserMapper.getUserByOrgUserCode(orgCode,userCode);
		if(null!=result){
			resp = new QueryOrgUsersResponse();
			BeanUtils.copyProperties(resp, result);
			resp.setRoleId(result.getSpecilRole());
		}
		return resp;
	}

	public String getUserAuthEvent(Client client) throws Exception {
		String userAuth = null;
		//获取到当前用户的角色是平台管理员
		if(UserRolesEnums.isXbdAdmin(client.getRoleId())){
			userAuth = orgUserMapper.orgUserAuthAdmin(client.getPlatCode());
		}else{
			userAuth = orgUserMapper.orgUserAuth(client.getPlatCode(),Long.valueOf(client.getUserCode()),client.getOrgCode());
		}
		return userAuth;
	}

	@Transactional
	public CreateUserByInviteCodeResult createUserByInviteCode(CreateUserByInviteCodeRequest request) throws Exception {
		CreateUserByInviteCodeResult result = new CreateUserByInviteCodeResult();
		XbdunPkgEnum enum1 = XbdunPkgEnum.getEnum(request.getPakagetName());
		long qrOrgCode = NumberUtils.toLong(request.getQrOrgCode());
		if(null==enum1){
			result.setBizException(BizException.PARAM_CHKE_FAIL.newInstance("您所登录平台不是系统定义平台"));
			return result;
		}
		//
		XbdunOrgInviteCodeDo xbdunOrgInviteCodeById = null;
		if(qrOrgCode>0){
			xbdunOrgInviteCodeById = orgInviteCodeMapper.getXbdunOrgInviteCodeByOrg(qrOrgCode, request.getInviteCode());
		}else{
			xbdunOrgInviteCodeById = orgInviteCodeMapper.getXbdunOrgInviteCodeById(request.getIdCard(), request.getInviteCode());
		}
		if(null==xbdunOrgInviteCodeById){
			result.setBizException(BizException.DB_SELECTONE_IS_NULL.newInstance("您输入的身份号与邀请码不匹配，请重新输入"));
			return result;
		}
		//如果时间超过当前时间，那么就意味着过期
		if(null!=xbdunOrgInviteCodeById.getEndTime()&&(new Date().compareTo(xbdunOrgInviteCodeById.getEndTime()) ==1)){
			orgInviteCodeMapper.deleteInviteCode(xbdunOrgInviteCodeById.getId());
			result.setBizException(BmpBizException.DATA_OVER_TIME.newInstance("您的邀请码已经在%s过期,请重新到企业那里认领.",DateUtil.getReqDate(xbdunOrgInviteCodeById.getEndTime())));
			return result;
		}else if(xbdunOrgInviteCodeById.getPlatType()==PlatTypeEnum.BUSI.getKey()&&!XbdunPkgEnum.ENTERPRISE.equals(enum1)){
			//如果为企业，就需要判断服务包是那里来的
			result.setBizException(BizException.PARAM_CHKE_FAIL.newInstance("对不起，请使用企业版本应用登录"));
			return result;
		}else if(xbdunOrgInviteCodeById.getPlatType()==PlatTypeEnum.TRANSMAN.getKey()&&!XbdunPkgEnum.TRANSPORTER.equals(enum1)){
			//如果为企业，就需要判断服务包是那里来的
			result.setBizException(BizException.PARAM_CHKE_FAIL.newInstance("对不起，请使用运输员版本应用登录"));
			return result;
		}
		//修改用户基本信息
		if(0==sysUserBiz.updateUserByInvite(xbdunOrgInviteCodeById.getUserCode(),request.getWxUnionId(),request.getWxOpenId(),NumberUtils.createBigDecimal(request.getLatitude()),NumberUtils.createBigDecimal(request.getLongitude()))){
			result.setBizException(BizException.PARAM_CHKE_FAIL.newInstance("对不起，该邀请码未能找寻到用户信息"));
			return result;
		}
		//删除邀请码信息
		orgInviteCodeMapper.deleteInviteCode(xbdunOrgInviteCodeById.getId());
		//设置返回值
		result.setData(new CreateUserByInviteCodeResponse());
		result.getData().setOrgCode(xbdunOrgInviteCodeById.getOrgCode()+"");
		result.getData().setUserCode(xbdunOrgInviteCodeById.getUserCode()+"");
		return result;
	}

	public Map<Long,Integer> joinOrgCodes(String userCode,String wxUnionId){
		Map<Long,Integer> result = null;
		Long userCdong = null;
		if(StringUtils.isNotBlank(wxUnionId)){
			userCdong = sysUserBiz.getUserCodeByUnion(wxUnionId);
			if(null==userCdong){
				return null;
			}
		}
		//判断用户编号与用户的UnionId是否匹配
		if(StringUtils.isNotBlank(userCode)){
			if(null!=userCdong&&!userCode.equals(userCdong+"")){
				log.error("获取的用户编号与用户的UnionId不匹配,数据库用户编号【"+userCdong+"】,参数用户编号【"+userCode+"】");
				return null;
			}
			userCdong = Long.valueOf(userCode);
		}
		//查询出已经参与的机构编号
		List<JoinOrgCodeByCodeDto> joinOrgCodeByCode = orgUserMapper.joinOrgCodeByCode(userCdong+"");
		if(CollectionUtils.isNotEmpty(joinOrgCodeByCode)){
			result = new HashMap<Long,Integer>();
			for(JoinOrgCodeByCodeDto item:joinOrgCodeByCode){
				result.put(item.getOrgCode(), item.getBlDel());
			}
			joinOrgCodeByCode.clear();
			joinOrgCodeByCode = null;
		}
		return result;
	}

	public void inviteOrgUser(String userId, int inviteType, Client client) throws Exception {
		XbdunOrgUserDo byUserId = orgUserMapper.getByUserId(userId);
		if(null ==byUserId){
			throw BizException.DB_SELECTONE_IS_NULL.newInstance("操作的用户不存在");
		}
		XbdunSysUserDo userDo = sysUserBiz.getByUserCode(byUserId.getUserCode());
		if(null ==userDo){
			throw BizException.DB_SELECTONE_IS_NULL.newInstance("操作的用户不存在");
		}
		
		Map<String,Object> param = new HashMap<String,Object>();
		param.put("invitType", inviteType);
		Map<String, Object> where = new HashMap<String, Object>();
		where.put("userId", byUserId.getUserId());
		where.put("version", byUserId.getVersion());
		if (orgUserMapper.modifyOrgUserById(param, where)==0) {
			where.clear();
			param.clear();
			where = null;
			param = null;
			throw BizException.DB_UPDATE_RESULT_0.newInstance("修改当前用户失败");
		}
		where.clear();
		param.clear();
		where = null;
		param = null;
		
		//删除邀请码
		orgInviteCodeMapper.deleteInviteCodeByUserIdAndOrgCode(byUserId.getUserCode(), client.getOrgCode());
		if(inviteType>1){
			//创建邀请码
			XbdunOrgInviteCodeDo xbdunOrgInviteCodeDo = new XbdunOrgInviteCodeDo();
			
			xbdunOrgInviteCodeDo.setCreateTime(new Date());
			xbdunOrgInviteCodeDo.setIdCard(userDo.getIdCard());
			xbdunOrgInviteCodeDo.setInviteCode(RandomStringUtils.randomNumeric(6));
			xbdunOrgInviteCodeDo.setOrgCode(client.getOrgCode());
			xbdunOrgInviteCodeDo.setUserCode(userDo.getUserCode());
			xbdunOrgInviteCodeDo.setPlatType(PlatTypeEnum.SALESMAN.getKey());
			//邀请码有效期,过了这个有效期，那么就视为无效,就需要企业在此发放
			xbdunOrgInviteCodeDo.setEndTime(DateUtil.addDay(xbdunOrgInviteCodeDo.getCreateTime(), CommonConst.INVITE_CODE_DAT));
			
			//写入邀请码表信息
			orgInviteCodeMapper.addXbdunOrgInviteCode(xbdunOrgInviteCodeDo);
		}
	}

	public OrgUserBkgeResponse getOrgUserBkge(long orgCode, long userCode) {
		OrgUserBkgeResponse result = null;
		OrgUserBkgeDto dto = orgUserMapper.getOrgUserBkge(orgCode,userCode);
		if(null!=dto){
			result = new OrgUserBkgeResponse();
			result.setInauType(dto.getInauType());
			result.setSpecilRole(dto.getSpecilRole());
			dto = null;
		}
		return result;
	}

	public QueryOrgUsersResponse getUserIsWork(Long orgCode, Long userCode) throws Exception {
		QueryOrgUsersResponse resp = null;
		QueryOrgUsersDto result = orgUserMapper.getUserIsWork(orgCode,userCode);
		if(null!=result){
			resp = new QueryOrgUsersResponse();
			BeanUtils.copyProperties(resp, result);
			resp.setRoleId(result.getSpecilRole());
		}
		return resp;
	}
}
